import { Injectable, NotFoundException } from "@nestjs/common";
import { In, Like, Repository } from "typeorm";
import { ResultData } from "@/common/utils/result";
import { instanceToPlain } from "class-transformer";
import { InjectRepository } from "@nestjs/typeorm";
import { StudentInoutMessage } from "./entities/student-inout-message.entity";

@Injectable()
export class StudentInoutMessageService {
  constructor(
    @InjectRepository(StudentInoutMessage)
    private readonly studentInoutMessageRepo: Repository<StudentInoutMessage>,
  ) {}

  async create(createDto: Partial<StudentInoutMessage>) {
    const entity = this.studentInoutMessageRepo.create(createDto);
    const saved = await this.studentInoutMessageRepo.save(entity);
    return ResultData.ok(instanceToPlain(saved));
  }

  async findAll(query: { page?: number; size?: number; [key: string]: any; }) {
    const {
      page = 1,
      size = 15,
    } = query;

    const take = +size;
    const skip = (+page - 1) * take;
    const where = {
            // ...(status === 0 || status ? { status } : null),
            // ...(username ? { username: Like(`%${username}%`) } : null)
        };
    const [row, total] = await this.studentInoutMessageRepo.findAndCount({
      where,
      skip,
      take,
      order: { id: "DESC" },
    });

    return ResultData.ok({
      row: instanceToPlain(row),
      total,
      page: +page,
      size: take,
      pages: Math.ceil(total / take),
    });
  }

  async findOne(id: number) {
    const entity = await this.studentInoutMessageRepo.findOneBy({ id });
    if (!entity) {
      throw new NotFoundException(`海康人脸进出记录（ID：${id}）不存在`);
    }
    return ResultData.ok(instanceToPlain(entity));
  }

  async update(id: number, updateDto: Partial<StudentInoutMessage>) {
    await this.studentInoutMessageRepo.update(id, updateDto);
    return ResultData.ok(null, "更新成功");
  }

  async removeBatch(ids: number[]) {
    if (ids.length === 0) return ResultData.ok(null, "无数据需删除");
    const existCount = await this.studentInoutMessageRepo.countBy({ id: In(ids) });
    return ResultData.ok(await this.studentInoutMessageRepo.delete(ids), `成功删除${existCount}条海康人脸进出记录数据`);
  }

  async remove(id: number) {
    return ResultData.ok(await this.studentInoutMessageRepo.delete(id), `删除海康人脸进出记录成功`);
  }
}